import axios from 'axios';
import { BASE_API_URL, REQUEST_TOKEN_KEY } from '../utils/constants.ts';

import { getToken } from '../utils/app.ts';

// create an axios instance
const axiosIns = axios.create({
  baseURL: BASE_API_URL, // url = base url + request url
  timeout: 310000, // request timeout
});

// request interceptor
axiosIns.interceptors.request.use(
  (config) => {
    // 将get请求参数中的值为 空字符串与null的参数去掉
    if (config.method === 'get' && config.params) {
      Object.keys(config.params).forEach((key) => {
        if (config.params[key] === '' || config.params[key] === null) {
          delete config.params[key];
        }
      });
    }
    // 请求头增加token参数
    config.headers[REQUEST_TOKEN_KEY] = getToken();
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  },
);

// response interceptor
axiosIns.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 10000) {
      if (res.code === 50000) {
        // token timeout & to re-login
      } else {
      }
      return Promise.reject(res);
    } else {
      return res;
    }
  },
  (error) => {
    console.log('err' + error); // for debug
    return Promise.reject(error);
  },
);

export default axiosIns;
